const Router = require("koa-router");
const { IdCard } = require("@models/idcard");
const { User } = require("@models/user");
const { Auth } = require("@middlewares/auth");
const { IdCardvalidator } = require("@services/idcard");
const { operatorPoint } = require("@services/operatorPoint");
//IdCard.sync({ force: true });

const router = new Router({
  prefix: "/v1/idcheck",
});

router.post("/creat", new Auth().m, async (ctx) => {
  const { cardno, realname } = ctx.request.body;
  if (!cardno && !realname) {
    throw new global.errs.ParameterException("参数错误");
  }
 let regex = /^[\u4e00-\u9fa5]{2,}$/;
 if (!regex.test(realname)) {
   throw new global.errs.ParameterException("姓名错误");
 }
  // 解析效验身份证信息
  const data = IdCardvalidator.IdentityCodeValid(cardno);
  if (!data) {
    throw new global.errs.AuthFailed("身份证格式错误");
  }
  const card = await IdCard.findOne({ where: { cardno } });
  if (card) {
    throw new global.errs.AlreadyExists("身份证已被绑定");
  }

  const user = await User.findOne({ where: { uid: ctx.auth.uid } });
  if (user.eid) {
    throw new global.errs.AlreadyExists("已绑定身份证");
  }

  const idcard = await IdCard.create({ cardno, realname, ...data });
  await user.update({ eid: idcard.eid });
  // 随机积分返利
  let min = Math.ceil(1);
  let max = Math.floor(10);
  let point = Math.floor(Math.random() * (max - min + 1)) + min;

  // 首次绑定身份奖励积分
  await operatorPoint.add(user, point, "完善信息随机返利");
  ctx.body = {
    code: 200,
    msg: "success",
    data,
  };
});
module.exports = router;
